package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //发起微信登录的第三方请求
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        //解析请求结果
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = (String) jsonObject.get("openid");
        if(openid.isEmpty()){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //查询用户是否第一次登录
        User user = userMapper.getByOpenId(openid);
        if(Objects.isNull(user)){
            user = new User();
            user.setName(openid.substring(0,5));
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openid);
            userMapper.insert(user);
        }
        return user;
    }
}
